package com.groupware.member.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.groupware.member.model.MemberModel;
import com.groupware.member.service.MemberService;
import com.groupware.member.service.MemberValidatior;

@Controller
@RequestMapping("/member")
public class MemberController {
	private ApplicationContext context;
	
	@RequestMapping(value = "/join1.do", method = RequestMethod.GET)
	public String main(HttpServletRequest request, HttpServletResponse response) {
		
		return "/board/join1";
	}
	@RequestMapping(value = "/userIdcheck.do", method = RequestMethod.GET)
	public String idcheck(){
		return "/board/userIdcheck";
	}
	@RequestMapping(value = "/logformproc.do", method = RequestMethod.GET)
	public String logformproc(){
		return "/board/logformproc";
	}
	@RequestMapping(value = "/regsuccess.do", method = RequestMethod.GET)
	public String regsuccess(){
		return "/board/regsuccess";
	}
	
	@RequestMapping("/join.do")
	public String memberloginjoin(){
		return "/board/join";
	}
	@RequestMapping("/logformproc.do")
	public String memberlogformproc(){
		return "/board/logformproc";
	}
	
	@RequestMapping(value="/join.do", method = RequestMethod.POST)
	public ModelAndView addMember(@ModelAttribute("MemberModel") MemberModel memberModel, BindingResult result){
		ModelAndView mav = new ModelAndView();
		new MemberValidatior().validate(memberModel, result);
		if(result.hasErrors()){
			mav.setViewName("/board/join");
			return mav;
		}
	context = new ClassPathXmlApplicationContext("/config/applicationContext.xml");
	MemberService memberService = (MemberService) context.getBean("memberService");
	MemberModel checkMemberModel = memberService.findByUserId(memberModel.getUserId());
	
	if(checkMemberModel != null){
		mav.addObject("errCode", 1); // userId already exist 
		mav.setViewName("/board/join");
		return mav;
	}
	
	if(memberService.addMember(memberModel)){
		mav.addObject("errCode", 3);
		mav.setViewName("/board/login"); // success to add new member; move to login page
		return mav;
	} else {
		mav.addObject("errCode", 2); // failed to add new member
		mav.setViewName("/board/join");
		return mav;
		}
  }
	
	
}
